package com.graduation.check.service;

import com.graduation.check.dto.DashboardStatsResponse;
import com.graduation.check.entity.ExtractionStats;
import com.graduation.check.entity.PaperExtractionTask;
import com.graduation.check.mapper.PaperExtractionTaskMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

@Slf4j
@Service
public class PaperInfoExtractionStatsService {

    @Autowired
    private PaperExtractionTaskMapper paperExtractionTaskMapper;

    /**
     * 获取信息提取统计（真实数据）
     */
    public DashboardStatsResponse getExtractionStats(Long studentId) {
        try {
            log.info("获取信息提取统计 - 学生ID: {}", studentId);

            ExtractionStats stats = paperExtractionTaskMapper.findStatsByStudentId(studentId);
            DashboardStatsResponse response = new DashboardStatsResponse();

            if (stats != null) {
                response.setExtractionCount(stats.getTotalCount() != null ? stats.getTotalCount() : 0L);

                // 设置最近提取时间
                if (stats.getLastExtractTime() != null) {
                    response.setLastCheckTime(stats.getLastExtractTime());
                    // 计算最近提取天数
                    long daysBetween = ChronoUnit.DAYS.between(stats.getLastExtractTime(), LocalDateTime.now());
                    response.setLastCheckDays(Math.max(0, (int) daysBetween));
                } else {
                    response.setLastCheckTime(null);
                    response.setLastCheckDays(0);
                }
            } else {
                response.setExtractionCount(0L);
                response.setLastCheckTime(null);
                response.setLastCheckDays(0);
            }

            log.info("信息提取统计结果: {}", response);
            return response;

        } catch (Exception e) {
            log.error("获取信息提取统计失败", e);
            DashboardStatsResponse response = new DashboardStatsResponse();
            response.setExtractionCount(0L);
            response.setLastCheckTime(null);
            response.setLastCheckDays(0);
            return response;
        }
    }
}